package com.aabte.springcloudlearn.ribbonhystrixcustomerdemo.filter;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 初始化Hystrix请求上下文过滤器
 * 注意：需要在过滤器类上添加{@link Configuration}注解才能生效
 *
 * @author Daniel
 */
@Configuration
@WebFilter(
        filterName = "hystrixRequestContextServletFilter",
        urlPatterns = "/*",
        asyncSupported = true
)
public class HystrixRequestContextServletFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // nothing
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 初始化Hystrix请求上下文
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        try {
            chain.doFilter(request, response);
        } finally {
            // 关闭Hystrix请求上下文
            context.shutdown();
        }
    }

    @Override
    public void destroy() {
        // nothing
    }
}
